package cn.linkstudy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.linkstudy.entity.AiQuestion;
import cn.linkstudy.entity.AiChat;
import cn.linkstudy.mapper.AiQuestionMapper;
import cn.linkstudy.mapper.AiChatMapper;
import cn.linkstudy.service.AiService;
import cn.linkstudy.service.DeepSeekService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.linkstudy.entity.ChatRecord;
import cn.linkstudy.mapper.ChatRecordMapper;

/**
 * AI服务实现类
 * 负责AI出题、对话、历史记录等业务逻辑
 */
@Slf4j
@Service
public class AiServiceImpl extends ServiceImpl<AiQuestionMapper, AiQuestion> implements AiService {

    @Autowired
    private DeepSeekService deepSeekService;

    @Autowired
    private AiChatMapper aiChatMapper;

    @Autowired
    private ChatRecordMapper chatRecordMapper;

    @Override
    public Map<String, Object> generateQuestion(Long userId, String subject, String grade, String difficulty) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 构建出题提示词
            String prompt = String.format(
                    "请为%s年级学生生成一道%s学科的%s难度题目。要求：\n" +
                            "1. 题目内容要符合该年级学生的认知水平\n" +
                            "2. 提供详细的答案和解析\n" +
                            "3. 格式要求：题目、答案、解析分别用【题目】、【答案】、【解析】标记\n" +
                            "4. 题目要有教育意义，能够帮助学生掌握知识点",
                    grade, subject, difficulty);

            // 调用AI生成题目
            String response = deepSeekService.chat(prompt);

            // 解析AI回复
            String questionContent = "";
            String answer = "";
            String explanation = "";

            if (response.contains("【题目】") && response.contains("【答案】") && response.contains("【解析】")) {
                String[] parts = response.split("【");
                for (String part : parts) {
                    if (part.startsWith("题目】")) {
                        questionContent = part.substring(3).trim();
                    } else if (part.startsWith("答案】")) {
                        answer = part.substring(3).trim();
                    } else if (part.startsWith("解析】")) {
                        explanation = part.substring(3).trim();
                    }
                }
            } else {
                // 如果没有按格式返回，直接使用回复内容作为题目
                questionContent = response;
            }

            // 保存到数据库
            AiQuestion aiQuestion = new AiQuestion();
            aiQuestion.setUserId(userId);
            aiQuestion.setSubject(subject);
            aiQuestion.setGrade(grade);
            aiQuestion.setDifficulty(difficulty);
            aiQuestion.setQuestionContent(questionContent);
            aiQuestion.setAnswer(answer);
            aiQuestion.setExplanation(explanation);

            save(aiQuestion);

            result.put("success", true);
            result.put("question", aiQuestion);

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成题目失败：" + e.getMessage());
        }

        return result;
    }

    @Override
    public String chat(Long userId, String sessionId, String message) {
        // 调用AI对话服务，保存对话记录
        try {
            // 调用AI对话
            String response = deepSeekService.chat(message);

            // 保存对话记录
            AiChat aiChat = new AiChat();
            aiChat.setUserId(userId);
            aiChat.setSessionId(sessionId);
            aiChat.setUserMessage(message);
            aiChat.setAiResponse(response);

            aiChatMapper.insert(aiChat);

            return response;
        } catch (Exception e) {
            return "抱歉，我遇到了一些问题，请稍后再试。";
        }
    }

    @Override
    public List<AiQuestion> getUserQuestions(Long userId) {
        // 查询用户的出题历史
        QueryWrapper<AiQuestion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .orderByDesc("create_time");
        return list(queryWrapper);
    }

    @Override
    public List<ChatRecord> getUserChats(Long userId, String sessionId) {
        // 查询用户的对话历史，返回ChatRecord类型
        // 这里假设有ChatRecordMapper和ChatRecord实体，按实际业务调整
        QueryWrapper<ChatRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        if (sessionId != null) {
            queryWrapper.eq("session_id", sessionId);
        }
        queryWrapper.orderByAsc("create_time");
        // 需要注入ChatRecordMapper
        return chatRecordMapper.selectList(queryWrapper);
    }

    @Override
    public AiChat getHistory(Long userId, String sessionId) {
        // 查询单个会话历史（如有多条，仅返回最新一条）
        QueryWrapper<AiChat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("session_id", sessionId)
                .orderByDesc("create_time")
                .last("LIMIT 1");
        return aiChatMapper.selectOne(queryWrapper);
    }

    @Override
    public String guideChatWithMessages(java.util.List<java.util.Map<String, String>> messages) {
        return deepSeekService.chatWithMessages(messages);
    }
}